<script setup lang="ts">
  import { ref, computed, onMounted } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { showToast, showSuccessToast } from 'vant';
  import YHeader from '@/components/YHeader.vue';
  
  interface Student {
    id: string;
    name: string;
    studentId: string;
    avatar?: string;
    email?: string;
    isActive: boolean;
  }
  
  const router = useRouter();
  const route = useRoute();
  const courseId = computed(() => route.query.courseId as string);
  
  const students = ref<Student[]>([
    { id: '1', name: '张三', studentId: '2021001', avatar: '', isActive: true, email: 'zhangsan@example.com' },
    { id: '2', name: '李四', studentId: '2021002', avatar: '', isActive: true, email: 'lisi@example.com' },
    { id: '3', name: '王五', studentId: '2021003', avatar: '', isActive: false, email: 'wangwu@example.com' },
  ]);
  
  const searchValue = ref('');
  const showAddStudent = ref(false);
  const showRemoveConfirm = ref(false);
  const studentToRemove = ref<Student | null>(null);
  const newStudent = ref({
    name: '',
    studentId: '',
    email: ''
  });
  
  const totalStudents = computed(() => students.value.length);
  const activeStudents = computed(() => students.value.filter(s => s.isActive).length);
  
  const filteredStudents = computed(() => {
    if (!searchValue.value) return students.value;
    
    const keyword = searchValue.value.toLowerCase();
    return students.value.filter(
      student => 
        student.name.toLowerCase().includes(keyword) || 
        student.studentId.toLowerCase().includes(keyword)
    );
  });
  
  onMounted(async () => {
    // 实际项目中这里应该调用API获取学生列表
    // if (courseId.value) {
    //   try {
    //     const res = await getStudentList(courseId.value);
    //     students.value = res.data;
    //   } catch (error) {
    //     console.error('获取学生列表失败', error);
    //   }
    // }
  });
  
  const onBack = () => {
    router.back();
  };
  
  const onSearch = () => {
    // 搜索功能实现
  };
  
  const addStudent = async () => {
    // 实际项目中这里应该调用API添加学生
    // try {
    //   await addStudentToCourse(courseId.value, newStudent.value);
    //   showSuccessToast('添加成功');
    //   // 重新获取学生列表
    // } catch (error) {
    //   console.error('添加学生失败', error);
    //   showToast('添加失败');
    // }
    
    // 模拟添加
    const id = String(Date.now());
    students.value.push({
      id,
      name: newStudent.value.name,
      studentId: newStudent.value.studentId,
      email: newStudent.value.email,
      isActive: false
    });
    
    showSuccessToast('添加成功');
    
    // 重置表单
    newStudent.value = {
      name: '',
      studentId: '',
      email: ''
    };
  };
  
  const confirmRemoveStudent = (student: Student) => {
    studentToRemove.value = student;
    showRemoveConfirm.value = true;
  };
  
  const removeStudent = async () => {
    if (!studentToRemove.value) return;
    
    // 实际项目中这里应该调用API移除学生
    // try {
    //   await removeStudentFromCourse(courseId.value, studentToRemove.value.id);
    //   showSuccessToast('移除成功');
    //   // 重新获取学生列表
    // } catch (error) {
    //   console.error('移除学生失败', error);
    //   showToast('移除失败');
    // }
    
    // 模拟移除
    students.value = students.value.filter(s => s.id !== studentToRemove.value?.id);
    showSuccessToast('移除成功');
  };
  </script>
<template>
    <div class="student-manage">
      <!-- <y-header title="学生管理" left-arrow @click-left="onBack" /> -->
      <YHeader></YHeader>
      <div class="search-bar">
        <van-search
          v-model="searchValue"
          placeholder="搜索学生姓名或学号"
          @search="onSearch"
        />
        <van-button type="primary" size="small" icon="plus" @click="showAddStudent = true">添加学生</van-button>
      </div>
      
      <div class="student-stats">
        <div class="stat-item">
          <span class="label">总人数</span>
          <span class="value">{{ totalStudents }}</span>
        </div>
        <div class="stat-item">
          <span class="label">活跃人数</span>
          <span class="value">{{ activeStudents }}</span>
        </div>
      </div>
      
      <div class="student-list">
        <van-empty v-if="students.length === 0" description="暂无学生" />
        
        <van-swipe-cell v-for="student in filteredStudents" :key="student.id">
          <van-cell>
            <template #title>
              <div class="student-item">
                <van-image
                  round
                  width="40"
                  height="40"
                  :src="student.avatar || 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'"
                />
                <div class="student-info">
                  <div class="student-name">{{ student.name }}</div>
                  <div class="student-id">学号: {{ student.studentId }}</div>
                </div>
              </div>
            </template>
            <template #right-icon>
              <van-icon name="arrow" />
            </template>
          </van-cell>
          <template #right>
            <van-button square type="danger" text="删除" @click="confirmRemoveStudent(student)" />
          </template>
        </van-swipe-cell>
      </div>
      
      <!-- 添加学生弹窗 -->
      <van-dialog
        v-model:show="showAddStudent"
        title="添加学生"
        show-cancel-button
        @confirm="addStudent"
      >
        <van-form>
          <van-field
            v-model="newStudent.name"
            name="name"
            label="姓名"
            placeholder="请输入学生姓名"
            :rules="[{ required: true, message: '请输入学生姓名' }]"
          />
          <van-field
            v-model="newStudent.studentId"
            name="studentId"
            label="学号"
            placeholder="请输入学号"
            :rules="[{ required: true, message: '请输入学号' }]"
          />
          <van-field
            v-model="newStudent.email"
            name="email"
            label="邮箱"
            placeholder="请输入邮箱"
            :rules="[{ required: true, message: '请输入邮箱' }]"
          />
        </van-form>
      </van-dialog>
      
      <!-- 删除确认弹窗 -->
      <van-dialog
        v-model:show="showRemoveConfirm"
        title="确认删除"
        show-cancel-button
        @confirm="removeStudent"
      >
        <p style="padding: 20px 16px;">确定要将学生 {{ studentToRemove?.name }} 从课程中移除吗？</p>
      </van-dialog>
    </div>
  </template>
  
  
  
  <style scoped>
  .student-manage {
    background-color: #f7f8fa;
    min-height: 100vh;
  }
  
  .search-bar {
    display: flex;
    align-items: center;
    padding: 0 16px;
    background: #fff;
  }
  
  .search-bar .van-search {
    flex: 1;
    padding: 10px 0;
  }
  
  .student-stats {
    display: flex;
    margin: 10px 16px;
    background: #fff;
    border-radius: 8px;
    overflow: hidden;
  }
  
  .stat-item {
    flex: 1;
    padding: 16px;
    text-align: center;
  }
  
  .label {
    display: block;
    font-size: 14px;
    color: #646566;
  }
  
  .value {
    display: block;
    font-size: 20px;
    font-weight: bold;
    margin-top: 5px;
    color: #1989fa;
  }
  
  .student-list {
    margin: 16px;
  }
  
  .student-item {
    display: flex;
    align-items: center;
  }
  
  .student-info {
    margin-left: 12px;
  }
  
  .student-name {
    font-size: 16px;
    font-weight: 500;
  }
  
  .student-id {
    font-size: 13px;
    color: #646566;
    margin-top: 4px;
  }
  </style>